package com.d3works.apps.supplychain.service;

import com.d3works.apps.crm.db.Opportunity;
import com.d3works.apps.sale.db.SaleOrder;
import com.d3works.apps.sale.service.saleorder.OpportunitySaleOrderServiceImpl;
import com.d3works.apps.supplychain.service.app.AppSupplychainService;
import com.d3works.exception.D3worksException;
import com.d3works.inject.Beans;
import com.google.inject.persist.Transactional;

public class OpportunitySaleOrderSupplychainServiceImpl extends OpportunitySaleOrderServiceImpl {

  @Override
  @Transactional(rollbackOn = {Exception.class})
  public SaleOrder createSaleOrderFromOpportunity(Opportunity opportunity) throws D3worksException {
    SaleOrder saleOrder = super.createSaleOrderFromOpportunity(opportunity);

    // Adding supplychain behaviour
    // Set default invoiced and delivered partners and address in case of partner delegations
    if (Beans.get(AppSupplychainService.class).getAppSupplychain().getActivatePartnerRelations()) {
      Beans.get(SaleOrderSupplychainService.class)
          .setDefaultInvoicedAndDeliveredPartnersAndAddresses(saleOrder);
    }

    saleOrderRepo.save(saleOrder);

    return saleOrder;
  }
}
